<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/1/5
 * Time: 11:29
 */

namespace iBrand\Shop\Core\Models;

use Illuminate\Database\Eloquent\Model;

class Refund extends Model
{
    protected $guarded = ['id'];

    const STATUS_COMPLETE = 1; //售后完成

    const TYPE_RETURN = 1;   //退货
    const TYPE_EXCHANGE = 2;    //换货

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $prefix = config('ibrand.app.database.prefix', 'ibrand_');
        $this->setTable($prefix . 'o2o_refund');
        $this->refund_no = build_order_no('R');
    }

    public function save(array $options = [])
    {
        $refund = parent::save($options); // TODO: Change the autogenerated stub

        $this->items()->saveMany($this->getItems());

        return $refund;
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function items()
    {
        return $this->hasMany(RefundItem::class);
    }

    public function getItems()
    {
        return $this->items;
    }

    public function hasItem(RefundItem $item)
    {
        return $this->items->contains(function ($value, $key) use ($item) {
            return $item->order_item_id == $value->order_item_id;
        });
    }

    public function addItem(RefundItem $item)
    {
        if ($this->hasItem($item)) {
            return;
        }
        $this->quantity += $item->quantity;
        $this->amount += $item->amount;
        $this->items->add($item);
    }

    public function payment()
    {
        return $this->hasMany(RefundPayment::class, 'refund_id');
    }

    public function clerk()
    {
        return $this->belongsTo(Clerk::class, 'clerk_id')->withDefault();
    }

    public function shop()
    {
        return $this->belongsTo(Shop::class);
    }
}